# -*- coding: utf-8 -*-
__author__ = 'guo'

import tornado.web
import pymongo
import re
import hashlib
import json
import time
from bson.objectid import ObjectId


class BaseHandle(tornado.web.RequestHandler):

    @property
    def getHotArticle(self):
        hotArticle = self.db.article.find().sort("looks", pymongo.DESCENDING).limit(6)
        return hotArticle


    def getCookie(self, key):
        return self.get_cookie(key)

    @property
    def GetXSRF(self):
        return self.get_cookie('_xsrf')

    @property
    def db(self):
        return self.application.db

    def get_current_user(self):
        if self.get_secure_cookie("userinfo") is not None:
            user = eval(self.get_secure_cookie("userinfo").decode("utf8"))[0]
            return user
        else:
            return None
    @property
    def getCatelog(self):
        cate = self.db.catelog.find()
        catelist = []
        if cate != None:
            catelist = self.Conver(cate)
        return catelist


    #
    # def input(self):
    #     from St
    #     i = storage()
    #     args = self.request.arguments
    #     for a in args:
    #         i[a] = self.get_argument(a)
    #     return i


    # @property
    # def xsrf_token(self):
    #     import  binascii
    #     if not hasattr(self, "_xsrf_token"):
    #         token = self.get_cookie("XSRF-TOKEN")
    #         if not token:
    #             token = binascii.b2a_hex(uuid.uuid4().bytes)
    #             expires_days = 30 if self.current_user else None
    #             self.set_cookie("XSRF-TOKEN", token, expires_days=expires_days)
    #         self._xsrf_token = token
    #     return self._xsrf_token
    #
    # def check_xsrf_cookie(self):
    #     token = (self.get_argument("_xsrf", None) or
    #              self.request.headers.get("X-XSRF-TOKEN") or
    #              self.request.headers.get("X-Xsrftoken"))
    #     # if not token:
    #     #     raise HTTPError(403, "'_xsrf' argument missing from POST")
    #     # if self.xsrf_token != token:
    #     #     raise HTTPError(403, "XSRF cookie does not match POST argument")




    def checkType(self, username=None):
        if username:
            #email
            if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", username) != None:
                    return "EMAIL"
            #mobile
            elif len(username)==11 and re.match("^(1[3458]\d{9})$", username) != None:
                return "MOBILE"
            #nick
            else:
                return "STR"
        else:
            return None

    def Conver(self, Dict=None, Iterative=True):

        ConverList = []

        if Iterative is True:
            for item in Dict:
                myJson = {}
                for x in item:
                    if x == "_id":
                        myJson['_id'] = str(ObjectId(item[x]))
                    elif x == "cid":
                        myJson['cid'] = str(ObjectId(item[x]))
                    else:
                        myJson[x] = str(item[x])
                ConverList.append(myJson)
        else:
            myJson = {}
            for x in Dict:
                if x == "_id":
                    myJson['_id'] = str(ObjectId(Dict[x]))
                else:
                    myJson[x] = str(Dict[x])
            ConverList.append(myJson)
        return ConverList

    def api_response(self, data):
        """将数据转成json返回给客户端"""
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        data = json.dumps(data)
        self.finish(data)

    def HashPwd(self, paswd):
        return hashlib.md5(paswd.strip().encode("utf8")).hexdigest()

    def TripString(self, Str):
        return Str.strip()

    def set_current_user(self, uname):
        userinfo = self.Conver(self.db.user.find_one({"uname": uname}), Iterative=False)
        self.set_secure_cookie("userinfo", str(userinfo), expires_days=None, expires=time.time()+900)



    def pagination(self, pageNum, pageSize=10):

        offset = (pageNum-1) * pageSize if pageNum >= 1 else 0
        data = {}
        result = self.db.article.find({'author': self.get_current_user()['uname']})
        data['count'] = result.count()
        data['article'] = result.skip(offset).limit(pageSize)

        import math
        pageAmount = math.ceil(data['count']/pageSize)


        # 上一页 下一页
        Previous = Next = ""
        if pageNum > 1:
            Previous = '<li class="previous"><a href="/user?pageNum=' + str(pageNum-1) + '">上一页</a></li>'

        if pageNum < pageAmount:
            Next = '<li class="next"><a href="/user?pageNum=' + str(pageNum+1) + '">下一页</a></li>'


        # 页码
        Li = ""
        for x in range(pageAmount):
            num = x+1
            if num == pageNum:
                Li += "<li class='active'><a href='/user?pageNum=" + str(num)+"'>" + str(num) + "</a></li>"
            else:
                Li += "<li><a href='/user?pageNum=" + str(num) + "'>" + str(num) + "</a></li>"

        pagination = "<ul class='pagination'>" + Previous + Li + Next + "</ul>"


        data['pagination'] = pagination
        return data